<?php
/**
 * Created by PhpStorm.
 * User: zhi
 * Date: 2016/4/29
 * Time: 10:38
 */
class Newjfpointsm extends CI_Model
{
    //添加 还是  减少
    const ADD_TYPE = 1;
    const MINUS_TYPE = 2;

    //业务类型
    const YEWU_DISUBJECT    = 1; //专题
    const YEWU_PART         = 2; //图谱

    //帖子类型
    const QUESTION_POST = 4; //问答
    const VOTE_POST = 5; //投票

    function __construct()
    {
        $this->parttime = $this->load->database('parttime', TRUE);
        $this->load->model('commentm');
        $this->load->model('userm');
        $this->load->model('postm');

        $this->config = array();
        $CI =& get_instance();

        if ($CI->config->load('jfpoints', TRUE, TRUE))
        {
            $this->config = $CI->config->item('jfpoints');
        }
        /*
         * 积分规则增加一个type字段 用来标识积分规则id  作为唯一标识来查询
         * 粉丝这些需要给批量加积分的行为 批量加积分
         * */
    }


    /**
     * 获取某个积分活动积分总数 当天
     * @param $uid
     * @param $type  积分规则id
     * @param int $related_type
     * @param int $related_id
     * @return array
     */
    public function get_today_jfpoints_count( $uid, $type, $related_type = 0, $related_id = 0)
    {
        //@TODO所有的次数限制或者上限限制 在积分函数里来做 方便查看和统计
        $start_time = strtotime("today");
        $end_time = strtotime("tomorrow");
        $this->db->select_sum('jfpoints');
        $this->db->where("addtime > ",$start_time);
        $this->db->where("addtime < ",$end_time);
        $this->db->where("adduser",$uid);
        $this->db->where("type",$type);
        if($related_type)
        {
            $this->db->where("related_type",$related_type);
        }
        if($related_id)
        {
            $this->db->where("related_id",$related_id);
        }

        $query = $this->db->get('ml_jfpoint_log');
        //echo $this->db->last_query();
        $result = $query->result_array();

        return $result;
    }

    /**
     * 获取某个积分活动次数 当天
     * @param $uid
     * @param $type  积分规则id
     * @param int $related_type
     * @param int $related_id
     * @param int $limit_rate
     * @return int
     */
    public function get_today_add_count( $uid, $type,$limit_rate, $related_type = 0, $related_id = 0)
    {

        $this->db->from('ml_jfpoint_log');


        if($limit_rate == "day")
        {
            $start_time = strtotime("today");
            $end_time = strtotime("tomorrow");
            $this->db->where("addtime > ",$start_time);
            $this->db->where("addtime < ",$end_time);
        }

        $this->db->where("adduser",$uid);
        $this->db->where("jfpoints > ",0);
        $this->db->where("type",$type);
        if($related_type)
        {
            $this->db->where("related_type",$related_type);
        }
        if($related_id)
        {
            $this->db->where("related_id",$related_id);
        }

        $result = $this->db->count_all_results();
//w_log($this->db->last_query());
        return $result;
    }


    /**
     * 获取某个积分是否获得过
     * @param $uid
     * @param $type  积分规则id
     * @param int $related_type
     * @param int $related_id
     * @return int
     */
    public function check_is_got( $uid, $type, $related_type = 0, $related_id = 0)
    {
        $this->db->select('jfpoints')->from('ml_jfpoint_log');
        $this->db->where("adduser",$uid);
        $this->db->where("type",$type);
        if($related_type)
        {
            $this->db->where("related_type",$related_type);
        }
        else
        {
            $this->db->where("related_id",$related_id);
        }

        $this->db->where("related_id",$related_id);

        $result = $this->db->order_by("id","desc")->get()->row_array();
        //w_log($this->db->last_query());
        $return = ($result && $result['jfpoints'] > 0) ? TRUE : FALSE;

        return $return;
    }

    

    /**
     * 根据config 获取积分规则的详情 给某个人加积分
     * @param $uid
     * @param $type  积分规则id
     * @param int $related_type
     * @param int $related_id  $related_id 必须能保证每条积分添加都是唯一的   $related_id类似关注这样的 就先不唯一了吧
     */
    public function add_jfpoints_for_one_user( $uid, $type, $related_id = 0,$related_type = 0)
    {
        if(empty($uid) || empty($type))
        {
            return array("code"=>-4,"message"=>"参数错误");
        }
//        //w_log('  ');//w_log('  ');
        //w_log('积分规则是 '.$type);
        //获取积分规则内容
        $stage                  = $this->config[$type]['stage'];
        $desc                   = $this->config[$type]['desc'];
        $one_time_jfpoints      = $this->config[$type]['one_time_jfpoints'];
        $check_relate_type      = $this->config[$type]['relate_type'];
        $check_relate_id        = $this->config[$type]['is_relate_id'];
        $limit_rate             = $this->config[$type]['limit_rate'];
        $limit_count            = $this->config[$type]['limit_count'];
        $is_cancel              = $this->config[$type]['is_cancel'];

        //如果有关联类型 需要
        if($check_relate_type && $check_relate_type != $related_type)
        {
            //w_log("关联类型不正确");
            return array("code"=>-3,"message"=>"关联类型不正确");
        }

        //如果有限制次数  及时间范围 需要查询次数
        $can_add_jfpoints = TRUE; //默认是可以添加积分的
        //w_log('$limit_rate && $limit_count is '.$limit_rate .'   '. $limit_count);
        if($limit_rate && $limit_count)
        {

                //如果不需要关联id  则不需要传入  $related_id  这个参数
                if($check_relate_id)
                {
                    //w_log('需要关联');
                    //检查是否获取过这个积分  如果是粉丝和收藏这种 检查最后一次获取积分是加还是 减  如果是加才能减  如果是减  则不能再减  $related_id 必须能保证每条积分添加都是唯一的
                    $check_is_got = $this->check_is_got( $uid, $type, $related_type, $related_id);
                    //w_log('$check_is_got is '.$check_is_got);
                    //没有加过分 才可以
                    if(!$check_is_got)
                    {
                        //如果有每天限制  则 不用检查每个id对应的规则次数  而是检查每天的获取这条规则的总数
                        //$related_id_send 这里不能用$related_id  不然会把这个变量重新赋值
                        if($limit_rate == "day")
                        {
                            $today_add_count = $this->get_today_add_count( $uid, $type,$limit_rate, $related_type, 0);
                        }
                        else
                        {
                            $today_add_count = $this->get_today_add_count( $uid, $type,$limit_rate, $related_type, $related_id);
                        }

                        //w_log('$today_add_count is '.$today_add_count);
                        $can_add_jfpoints = $today_add_count < $limit_count ? TRUE : FALSE;
                    }
                    else
                    {
                        $can_add_jfpoints =  FALSE;
                    }
                }
                else
                {
                    //不关联id的时候  related_id 需要为 0
                    //w_log('不需要关联');
                    $today_add_count = $this->get_today_add_count( $uid, $type, $limit_rate,$related_type, 0);
                    $can_add_jfpoints = $today_add_count < $limit_count ? TRUE : FALSE;
                    //w_log('$today_add_count is '.$today_add_count.'  $limit_count is '.$limit_count);
                    //w_log('$can_add_jfpoints is '.$can_add_jfpoints);
                }

        }

        //如果可以添加积分
        if($can_add_jfpoints)
        {
            //获取用户原来积分
            $uid_jfpoint = (float)$this->get_uid_jfpoints($uid);
            $add_data = [];
            $add_data['stage'] = $stage;
            $add_data['desc'] = $desc;
            $add_data['beforejfpoints'] = $uid_jfpoint;
            $add_data['jfpoints'] = $one_time_jfpoints;
            $add_data['resultjfpoints'] = $uid_jfpoint + $one_time_jfpoints;
            $add_data['adduser'] = $uid;
            $add_data['addtime'] = time();
            $add_data['related_id'] = $related_id;
            $add_data['related_type'] = $related_type;
            $add_data['type'] = $type;
//w_log(json_encode($add_data));
            $jfpoint_data = $this->insert_jfpoints($add_data);
            if($jfpoint_data)
            {
                //w_log($this->db->last_query());
                //w_log($add_data);
                return array("code"=>0,"message"=>"添加积分成功");
            }
            else
            {
                //w_log($this->db->last_query());
                //w_log($add_data);
                return array("code"=>-4,"message"=>"插入数据库失败");
            }

        }
        else
        {
            return array("code"=>-1,"message"=>"超过次数限制");
        }
    }


    /**
     * 减积分
     * @param $uid
     * @param $type
     * @param int $related_type
     * @param int $related_id   $related_id 必须能保证每条积分添加都是唯一的
     * @return array
     */
    public function minus_jfpoints_for_one_user( $uid, $type,  $related_id = 0,$related_type = 0)
    {
        if(empty($uid) || empty($type))
        {
            return array("code"=>-4,"message"=>"参数错误");
        }
        if($type == 1000)
        {
            //如果是封号或者禁言
            $minus_data = [];
            $minus_data['stage'] = '封号或禁言';
            $minus_data['desc'] = '封号或禁言清除所有积分';
            $minus_data['beforejfpoints'] = 0;
            $minus_data['jfpoints'] = 0;
            $minus_data['resultjfpoints'] = 0;
            $minus_data['adduser'] = $uid;
            $minus_data['addtime'] = time();
            $minus_data['related_id'] = 0;
            $minus_data['related_type'] = 0;
            $minus_data['type'] = $type;

            $jfpoint_data = $this->insert_jfpoints($minus_data);
            return array("code"=>0,"message"=>"取消积分成功");
        }
        else
        {
            //检查相关参数是否存在  不存在则不能减分  去后台  在stage里面说明情况 手动减分
            if(!$related_type || !$related_id)
            {
                //取消积分的项目 一定要有  $related_type 和 !$related_id
                return array("code"=>-2,"message"=>"缺少参数 related_type 或者 related_id");

            }
            //获取积分规则内容
            $stage                  = $this->config[$type]['stage'].'被取消';
            $desc                   = $this->config[$type]['desc'].'被取消';
            $one_time_jfpoints      = $this->config[$type]['one_time_jfpoints'];
            $check_relate_type      = $this->config[$type]['relate_type'];
            $check_relate_id        = $this->config[$type]['is_relate_id'];
            $limit_rate             = $this->config[$type]['limit_rate'];
            $limit_count            = $this->config[$type]['limit_count'];
            $is_cancel              = $this->config[$type]['is_cancel'];
//w_log('$is_cancel is '.$is_cancel);
            //可以取消才能取消积分
            if($is_cancel)
            {
                //检查是否获取过这个积分  如果是粉丝和收藏这种 检查最后一次获取积分是加还是 减  如果是加才能减  如果是减  则不能再减
                //如果是发布分享病例(60) 或者求助贴 (61) 还要检查是否是转移帖
                if ($type == 60)
                {
                    $check_is_got1 = $this->check_is_got( $uid, $type, 60, $related_id);
                    $check_is_got2 = $this->check_is_got( $uid, $type, 65, $related_id);
                    $check_is_got = ($check_is_got1 || $check_is_got2) ? 1 : 0;
                }
                elseif ($type == 61)
                {
                    $check_is_got1 = $this->check_is_got( $uid, $type, 61, $related_id);
                    $check_is_got2 = $this->check_is_got( $uid, $type, 66, $related_id);
                    $check_is_got = ($check_is_got1 || $check_is_got2) ? 1 : 0;
                }
                else
                {
                    $check_is_got = $this->check_is_got( $uid, $type, $related_type, $related_id);
                }
//w_log('是否获取过这个积分 '.$check_is_got);
                if($check_is_got)
                {
                    //获取用户原来积分
                    $uid_jfpoint = (float)$this->get_uid_jfpoints($uid);
                    $minus_data = [];
                    $minus_data['stage'] = $stage;
                    $minus_data['desc'] = $desc;
                    $minus_data['beforejfpoints'] = $uid_jfpoint;
                    $minus_data['jfpoints'] = -$one_time_jfpoints;
                    $minus_data['resultjfpoints'] = $uid_jfpoint - $one_time_jfpoints;
                    $minus_data['adduser'] = $uid;
                    $minus_data['addtime'] = time();
                    $minus_data['related_id'] = $related_id;
                    $minus_data['related_type'] = $related_type;
                    $minus_data['type'] = $type;

                    $jfpoint_data = $this->insert_jfpoints($minus_data);
                    return array("code"=>0,"message"=>"取消积分成功");
                }
                else
                {
                    return array("code"=>-3,"message"=>"积分已取消或没获取过");
                }


            }
            else
            {
                //w_log('没有获取过积分');
                //w_log($this->db->last_query());
                return array("code"=>-1,"message"=>"不可取消");
            }
        }

    }

    /**
     * 更新积分日志
     * @param $query  积分相关内容
     * @return object
     *
     */
    public function insert_jfpoints($query)
    {
        return $this->db->insert("ml_jfpoint_log", $query);
    }

    /**
     * 获取用户积分
     * @param $uid  要获取积分的用户id
     * @return int
     */
    public function get_uid_jfpoints($uid)
    {
        $result = $this->db->query("select resultjfpoints from  ml_jfpoint_log where adduser = ".$uid." order by id desc limit 1")->result_array();
        //$result = $this->db->where("adduser", $uid)->order_by("id", "desc")->limit(1, 0)->get("ml_jfpoint_log")->result_array();  //报错  Call to a member function result_array() on boolean
        return $result && $result[0] ? $result[0]["resultjfpoints"] : 0;
    }

    /**
     * 获取积分规则内容
     * @param $type  积分规则id
     * @return mixed
     */
    public function get_jfpoints_content($type)
    {
        //获取积分规则内容
        $return['stage']                  = $this->config[$type]['stage'];
        $return['desc']                   = $this->config[$type]['desc'];
        $return['one_time_jfpoints']      = $this->config[$type]['one_time_jfpoints'];
        $return['check_relate_type']      = $this->config[$type]['relate_type'];
        $return['check_relate_id']        = $this->config[$type]['is_relate_id'];
        $return['limit_rate']             = $this->config[$type]['limit_rate'];
        $return['limit_count']            = $this->config[$type]['limit_count'];
        $return['is_cancel']              = $this->config[$type]['is_cancel'];

        return $return;
    }

    /**
     * 获取最新的积分log id
     */
    public function get_last_id()
    {
        $result = $this->db->query("select id from  ml_jfpoint_log  order by id desc limit 1")->result_array();

        return $result[0]["id"];
    }

    /**
     * @param $toid  消息接受人 和积分加分对象
     * @param $related_id  相关id
     * @param $post_id
     * @param $addtype  加分还是减分
     */
    public function add_minusjf_sendmessage($toid,$post_id,$related_type,$related_id,$addtype)
    {
        //w_log(json_encode(array($toid,$post_id,$related_type,$related_id,$addtype)));
        $jfpoints_content = $this->get_jfpoints_content($related_type);
        //如果是加分
        ///w_log('$addtype is '.$addtype);
        //w_log('ADD_TYPE is  '.self::ADD_TYPE);
        //w_log('$related_type is '.$related_type);
        if($addtype == self::ADD_TYPE)
        {
            //w_log('加积分');
            $stage = $jfpoints_content['stage'];
            $result = $this->add_jfpoints_for_one_user($toid,$related_type,$related_id,$related_type);
        }
        else
        {
            $stage = $jfpoints_content['stage'].'被取消';
            $result = $this->minus_jfpoints_for_one_user($toid,$related_type,$related_id,$related_type);
        }
//w_log(json_encode($result));
        if($result['code'] == 0)
        {
            //发消息
            w_log("发消息");
            $msg_content = "[user:".$toid.": ]".$stage;
            w_log("message is ".$msg_content);
            $this->load->model('messagem');
            $this->messagem->send_message($post_id,$toid,$msg_content, "31495");

        }

        return $result;
    }

    /**
     * @param $toid
     * @param $related_type
     * @param $related_id 
     * @param $addtype 添加还是减少
     * @param int $yewu_type  业务类型
     */
    public function add_minusjf_sendmessage_noclick($toid,$related_type,$related_id,$addtype,$yewu_type=0)
    {
        $jfpoints_content = $this->get_jfpoints_content($related_type);
        //如果是加分
        //w_log('$addtype is '.$addtype);
        //w_log('ADD_TYPE is  '.self::ADD_TYPE);
        if($addtype == self::ADD_TYPE)
        {//w_log('加积分');
            $stage = $jfpoints_content['stage'];
            $result = $this->add_jfpoints_for_one_user($toid,$related_type,$related_id,$related_type);
        }
        else
        {
            $stage = $jfpoints_content['stage'].'被取消';
            $result = $this->minus_jfpoints_for_one_user($toid,$related_type,$related_id,$related_type);
        }

        
        if($result['code'] == 0){
            //发消息  给了积分才能发消息
            //根据业务发送不同的消息
            if($yewu_type == self::YEWU_DISUBJECT)
            {
                ci_load_once('disubjectm');
                $disubject_info = $this->disubjectm->get_one_disubject($related_id);
                $send_content = array("post_first_img"=>$disubject_info['small_img'],"content"=>$stage);
            }
            elseif ($yewu_type == self::YEWU_PART)
            {
                $package_info = $this->packagem->get_package_staic_content($related_id);
                $send_content = array("post_first_img"=>$package_info['atlas_cover'],"content"=>$stage);
            }
            else
            {
                $send_content = array("post_first_img"=>'http://static.medical-lighter.com/share/images/jfpoints.jpg',"content"=>$stage);
            }
            $send_content = json_encode($send_content);
            $this->messagem->send_msg_basic(31495, $toid, $send_content,$apptype=2,$msgtype=3);//默认用轻盈医学官方账号发送
        }
    }

    /**
     * 积分规则之外添加积分
     * @param $uid
     * @param $stage
     * @param $desc
     * @param $one_time_jfpoints
     * @param $type
     * @param int $related_id
     * @param int $related_type
     * @return array
     */
    public function add_jfpoints_out_config($uid, $stage, $desc, $one_time_jfpoints, $type, $related_id = 0, $related_type = 0, $dealuser = 0)
    {
        //获取用户原来积分
        $uid_jfpoint = (float)$this->get_uid_jfpoints($uid);
        $add_data = [];
        $add_data['stage'] = $stage;
        $add_data['desc'] = $desc;
        $add_data['beforejfpoints'] = $uid_jfpoint;
        $add_data['jfpoints'] = $one_time_jfpoints;
        $add_data['resultjfpoints'] = $uid_jfpoint + $one_time_jfpoints;
        $add_data['adduser'] = $uid;
        $add_data['addtime'] = time();
        $add_data['related_id'] = $related_id;
        $add_data['related_type'] = $related_type;
        $add_data['type'] = $type;
        $add_data['dealuser'] = $dealuser;
//w_log(json_encode($add_data));
        $jfpoint_data = $this->insert_jfpoints($add_data);
        if($jfpoint_data)
        {
            //w_log($this->db->last_query());
            //w_log($add_data);
            return array("code"=>0,"message"=>"添加积分成功");
        }
        else
        {
            //w_log('插入数据库失败  | '.$this->db->last_query());
            //w_log('插入数据库失败  | '.$add_data);
            return array("code"=>-4,"message"=>"插入数据库失败");
        }
    }

    /**
     * 选为最佳答案 积分变化
     * @param $post_type_extend
     * @param $comment_author_id
     * @param $post_id
     * @param $add_type
     *
     */
    public function invite_jf_change($post_type_extend,$comment_author_id,$post_id,$add_type)
    {
        if($post_type_extend == 1)
        {
            $jf_relate_type4 = DAILY_SHARE_POST_CHOISE_ANSWER;
        }
        elseif($post_type_extend == 3)
        {
            $jf_relate_type4 = DAILY_QUICK_POST_CHOISE_ANSWER;
        }
        elseif($post_type_extend == 4)
        {
            $jf_relate_type4 = DAILY_QUESTION_CHOICE_ANSWER;
        }

        $this->newjfpointsm->add_minusjf_sendmessage($comment_author_id,$post_id,$jf_relate_type4,$post_id,$add_type);
    }
    
    /***类结尾****/
}